package _1_1_Basic;

import org.junit.Test;

import java.math.BigDecimal;
/** 浮点数 */
public class _2_FloatingPoint {

    @Test
    public void infinity() {
        // POSITIVE_INFINITY  Double.NEGATIVE_INFINITY  Double.NaN
        // 看源码上的文档
        System.out.println(Double.POSITIVE_INFINITY);
        System.out.println(Double.NEGATIVE_INFINITY);

        System.out.println(2.0 - 1.1);
        // There is no precise binary representation of the fraction 1/10, just as there is
        // no accurate representation of the fraction 1/3 in the decimal system. If you need
        // precise numerical computations without round off errors, use the BigDecimal class.
    }

    @Test
    /**
     * @see BigDecimal#BigDecimal(double)
     */
    public void bigDecimal() {
        // 从double和float通过构造器创建的BigDecimal，也会造成精度丢失

        BigDecimal a = new BigDecimal(1.1);
        BigDecimal b = new BigDecimal(1.2);
        System.out.println(a.add(b));

        // 应该使用 valueOf() 方法，或者自己转为string
        double d = 1.024;
        BigDecimal bigDecimal = BigDecimal.valueOf(d);
        BigDecimal bigDecimal1 = bigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);
        System.out.println(bigDecimal1);


        BigDecimal bigDecimal2 = new BigDecimal(Double.toString(d));
        BigDecimal bigDecimal3 = bigDecimal2.setScale(2, BigDecimal.ROUND_HALF_UP);
        System.out.println(bigDecimal3);

        BigDecimal bigDecimal4 = BigDecimal.valueOf(0.12567);
        System.out.println(String.valueOf(bigDecimal4));
    }

}
